<template>
  <div>
    <el-collapse v-model="collapseActive" style="margin-bottom: 12px;">
      <el-collapse-item title="库位初始化" name="init">
        <el-form :inline="true" @submit.native.prevent>
          <el-form-item label="排数">
            <el-input-number v-model="initRows" :min="1" :max="20" />
          </el-form-item>
          <el-form-item label="列数">
            <el-input-number v-model="initColumns" :min="1" :max="20" />
          </el-form-item>
          <el-form-item label="层数">
            <el-input-number v-model="initLevels" :min="1" :max="10" />
          </el-form-item>
          <el-button type="primary" @click="initSlots">生成库位</el-button>
          <el-button type="danger" @click="clearAllSlots">清空全部库位</el-button>
        </el-form>
      </el-collapse-item>
      <el-collapse-item title="单个库位编辑" name="edit">
        <el-form :inline="true" @submit.native.prevent>
          <el-form-item label="排">
            <el-input-number v-model="form.row" :min="1" :max="rows" />
          </el-form-item>
          <el-form-item label="列">
            <el-input-number v-model="form.column" :min="1" :max="columns" />
          </el-form-item>
          <el-form-item label="层">
            <el-input-number v-model="form.level" :min="1" :max="levels" />
          </el-form-item>
          <el-form-item label="物料名称">
            <el-input v-model="form.name" />
          </el-form-item>
          <el-form-item label="数量">
            <el-input-number v-model="form.qty" :min="1" />
          </el-form-item>
          <el-form-item label="托盘号">
            <el-input v-model="form.pallet" placeholder="可选" />
          </el-form-item>
          <el-form-item label="长(m)">
            <el-input-number v-model="form.length" :min="0.1" :step="0.1" />
          </el-form-item>
          <el-form-item label="宽(m)">
            <el-input-number v-model="form.width" :min="0.1" :step="0.1" />
          </el-form-item>
          <el-form-item label="高(m)">
            <el-input-number v-model="form.height" :min="0.1" :step="0.1" />
          </el-form-item>
          <el-form-item label="承重(kg)">
            <el-input-number v-model="form.maxLoad" :min="1" :step="10" />
          </el-form-item>
          <el-button type="primary" @click="updateSlot">更新库位</el-button>
          <el-button @click="clearSlot">清空库位</el-button>
        </el-form>
      </el-collapse-item>
      <el-collapse-item title="库位定位" name="locate">
        <el-form :inline="true" @submit.native.prevent>
          <el-form-item label="排">
            <el-input-number v-model="locateForm.row" :min="1" :max="rows" />
          </el-form-item>
          <el-form-item label="列">
            <el-input-number v-model="locateForm.column" :min="1" :max="columns" />
          </el-form-item>
          <el-form-item label="层">
            <el-input-number v-model="locateForm.level" :min="1" :max="levels" />
          </el-form-item>
          <el-form-item label="托盘号">
            <el-input v-model="locateForm.pallet" placeholder="可选，支持直接输托盘号定位" />
          </el-form-item>
          <el-form-item label="物料名称">
            <el-input v-model="locateForm.name" placeholder="可选，支持物料名称定位" />
          </el-form-item>
          <el-button type="primary" @click="locateSlot">定位并查看库位</el-button>
        </el-form>
      </el-collapse-item>
    </el-collapse>
    <el-button type="info" @click="reset3DView" style="margin-bottom: 12px;">重置视角</el-button>
    <el-dialog :visible.sync="locateDialogVisible" title="选择库位" width="350px" @close="locateDialogVisible=false">
      <el-table :data="locateResultSlots" style="width: 100%" @row-click="chooseLocatedSlot">
        <el-table-column prop="row" label="排" width="50" />
        <el-table-column prop="column" label="列" width="50" />
        <el-table-column prop="level" label="层" width="50" />
        <el-table-column prop="status" label="状态" :formatter="statusFormat" />
      </el-table>
    </el-dialog>
    <Warehouse3D ref="warehouse3d" :slots="slots" :rows="rows" :columns="columns" :levels="levels" :external-selected-slot="externalSelectedSlot" :highlight-slots="highlightSlots" @clear-external-selected="externalSelectedSlot = null" />
  </div>
</template>

<script>
import Warehouse3D from './components/Warehouse3D.vue'
import { Message } from 'element-ui'

export default {
  components: {
    Warehouse3D
  },
  data() {
    return {
      collapseActive: ['locate'],
      initRows: 3,
      initColumns: 4,
      initLevels: 2,
      slots: [],
      form: { 
        row: 1, 
        column: 1, 
        level: 1, 
        name: '', 
        qty: 1, 
        pallet: '', 
        length: 1.2, 
        width: 1.2, 
        height: 1.2, 
        maxLoad: 1000 
      },
      locateForm: { 
        row: null, 
        column: null, 
        level: null, 
        pallet: '', 
        name: '' 
      },
      externalSelectedSlot: null,
      highlightSlots: [],
      locateDialogVisible: false,
      locateResultSlots: []
    }
  },
  computed: {
    rows() {
      return this.initRows
    },
    columns() {
      return this.initColumns
    },
    levels() {
      return this.initLevels
    }
  },
  methods: {
    initSlots() {
      this.slots = []
      for (let l = 0; l < this.initLevels; l++) {
        for (let r = 0; r < this.initRows; r++) {
          for (let c = 0; c < this.initColumns; c++) {
            this.slots.push({
              row: r + 1,
              column: c + 1,
              level: l + 1,
              status: 'empty',
              material: null,
              length: 1.2,
              width: 1.2,
              height: 1.2,
              maxLoad: 1000
            })
          }
        }
      }
    },
    updateSlot() {
      const idx = this.slots.findIndex(
        s => s.row === this.form.row && s.column === this.form.column && s.level === this.form.level
      )
      if (idx !== -1) {
        this.slots[idx].material = {
          name: this.form.name,
          qty: this.form.qty,
          ...(this.form.pallet ? { pallet: this.form.pallet } : {})
        }
        this.slots[idx].status = 'occupied'
        this.slots[idx].length = this.form.length
        this.slots[idx].width = this.form.width
        this.slots[idx].height = this.form.height
        this.slots[idx].maxLoad = this.form.maxLoad
      }
    },
    clearSlot() {
      const idx = this.slots.findIndex(
        s => s.row === this.form.row && s.column === this.form.column && s.level === this.form.level
      )
      if (idx !== -1) {
        this.slots[idx].material = null
        this.slots[idx].status = 'empty'
      }
    },
    clearAllSlots() {
      this.slots.forEach(slot => {
        slot.material = null
        slot.status = 'empty'
      })
    },
    reset3DView() {
      this.$refs.warehouse3d?.resetView()
    },
    locateSlot() {
      let slotsFound = []
      if (this.locateForm.pallet) {
        slotsFound = this.slots.filter(s => s.material && s.material.pallet === this.locateForm.pallet)
      } else if (this.locateForm.name) {
        const keyword = this.locateForm.name.trim().toLowerCase()
        slotsFound = this.slots.filter(s => s.material && s.material.name && s.material.name.toLowerCase().includes(keyword))
      } else if (this.locateForm.row && this.locateForm.column && this.locateForm.level) {
        slotsFound = this.slots.filter(s => s.row === this.locateForm.row && s.column === this.locateForm.column && s.level === this.locateForm.level)
      }
      if (slotsFound.length === 1) {
        this.externalSelectedSlot = slotsFound[0]
        this.highlightSlots = [slotsFound[0]]
      } else if (slotsFound.length > 1) {
        this.locateResultSlots = slotsFound
        this.locateDialogVisible = true
        this.highlightSlots = slotsFound
      } else {
        Message.warning('未找到对应库位')
        this.highlightSlots = []
      }
    },
    chooseLocatedSlot(slot) {
      this.externalSelectedSlot = slot
      this.locateDialogVisible = false
    },
    statusFormat(row, column, cellValue) {
      const map = { empty: '空库位', occupied: '已占用', reserved: '预留' }
      return map[cellValue] || cellValue
    }
  },
  created() {
    this.initSlots()
  }
}
</script>